package net.khoroshev.wschat.config;

import net.khoroshev.wschat.dao.JBDCProvider;
import net.khoroshev.wschat.service.auth.AuthUserManager;
import net.khoroshev.wschat.service.auth.Authorities;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;


import javax.sql.DataSource;


@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private static Log log = LogFactory.getLog(WebSecurityConfig.class);

    @Autowired
    DataSource dataSource;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
			.authorizeUrls()
				.antMatchers("/assets/**",
                        "/info/**",
                        "/login",
                        "/signup"
                ).permitAll()
                .antMatchers("/**").hasAuthority(Authorities.ROLE_USER)
                .antMatchers("/sessionInfo/usersOnline").hasAuthority(Authorities.ROLE_USER)
				.antMatchers("/sessionInfo/list").hasAuthority(Authorities.ROLE_ADMIN)
				.antMatchers("/chatHistory").hasAuthority(Authorities.ROLE_USER)
				.anyRequest().authenticated()
                .and()
			.logout()
                .deleteCookies("JSESSIONID")
                .invalidateHttpSession(true)
				.logoutSuccessUrl("/login?logout")
				.logoutUrl("/logout")
				.permitAll()
				.and()
			.formLogin()
				.defaultSuccessUrl("/index.html")
				.loginUrl("/login")
				.failureUrl("/login?error")
				.permitAll()
                .and()
            .sessionManagement()
                .invalidSessionUrl("/login")
                .sessionAuthenticationErrorUrl("/login")
                .maximumSessions(1)
        ;

	}

    @Bean
    public AuthUserManager userDetailManager() {
        return new AuthUserManager(new JBDCProvider(dataSource));
    }


    @Override
    protected void registerAuthentication(AuthenticationManagerBuilder auth)
			throws Exception {

        /*auth.inMemoryAuthentication()
          .withUser("vfirstov").password("vfirstov").roles("ADMIN","USER").and()
          .withUser("ikhoroshev").password("ikhoroshev").roles("ADMIN","USER");*/



        auth.userDetailsService(userDetailManager());


//        auth.authenticationProvider(new AuthenticationProvider() {
//
//            @Override
//            public boolean supports(Class<?> authentication) {
//                return true;
//            }
//
//            @Override
//            public Authentication authenticate(Authentication authentication)
//                    throws AuthenticationException {
//                List<GrantedAuthority> authorities = new ArrayList<>();
//                authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
//                UsernamePasswordAuthenticationToken newAuth
//                    = new UsernamePasswordAuthenticationToken(
//                            authentication.getPrincipal(),
//                            authentication.getCredentials(),
//                            authorities );
//                newAuth.setDetails(authentication.getDetails());
//                return newAuth;
//            }
//        });

	}
}